package com.monster.starter.core.utils;

import jakarta.servlet.http.HttpServletRequest;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

/**
 * url与方法的映射
 *
 * @author kuang
 */
@Slf4j
@Component
public class RequestMappingUtils {
    /**
     * spring mapping对象
     */
    @Getter
    public static RequestMappingHandlerMapping mapping;
    @Autowired
    private void setMapping (RequestMappingHandlerMapping mapping) {
        RequestMappingUtils.mapping = mapping;
    }

    /**
     * 获取处理链路
     * @param request 请求
     * @return HandlerExecutionChain
     * @throws Exception
     */
    public static HandlerExecutionChain getHandlerExecutionChain (HttpServletRequest request) {
        try {
            return mapping.getHandler(request);
        } catch (Exception e) {
            log.info("通过请求没有获取到相应的执行方法");
        }
        return null;
    }

    /**
     * 获取映射方法
     * @param request 请求对象
     * @return 映射方法
     */
    public static HandlerMethod getHandlerMethod (HttpServletRequest request) {
        HandlerExecutionChain chain = getHandlerExecutionChain(request);
        if (chain == null) {
            log.info("通过请求没有获取到相应的执行方法");
            return null;
        }
        Object handler = chain.getHandler();
        return chain == null ? null : handler instanceof HandlerMethod ? (HandlerMethod) handler : null;
    }
}
